package com.wingy.myservicedemo;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.Calendar;

public class myServiceDemoActivity extends AppCompatActivity implements View.OnClickListener{

    private static myServiceDemoActivity appRef = null;
    private Button btnA, btnB;
    boolean k = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appRef = this;
        setContentView(R.layout.activity_my_service_demo);

        btnA = (Button) findViewById(R.id.btnA);
        btnA.setOnClickListener(this);
        btnB = (Button) findViewById(R.id.btnB);
        btnB.setOnClickListener(this);
    }

    public static myServiceDemoActivity getApp() {return appRef; }

    public void btEvent(String data) {setTitle(data);}

    @Override
    public void onClick(View v) {
        if(v == btnA) {
            setTitle("等5秒~");
            Intent intent = new Intent(myServiceDemoActivity.this, AlarmReceiver.class);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(myServiceDemoActivity.this, 0, intent, 0);

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 5);

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }

        if(v == btnB) {
            Intent intent = new Intent(myServiceDemoActivity.this, AlarmReceiver.class);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(myServiceDemoActivity.this, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
            finish();
        }
    }
}
